package com.sdksoft.readcard

import com.csht.constants.Constant
import com.csht.enums.ReadCardType
import com.csht.enums.StatusCode
import com.csht.listener.InitListener
import com.csht.local.usb.UsbHidDevice
import com.csht.utils.BytesUtils
import com.csht.utils.DevicesUtils

class UsbActivity : BaseIDCardActivity(), InitListener {

    private var initSuccess = false

    override fun initView() {
        super.initView()
        setTitleText("USB读卡")
        intent.getStringExtra("readType")?.let {
            when (it) {
                "1" -> {
                    readSettingBuilder.buildReadCardType(ReadCardType.USB_XZKJ)
                }
                "2" -> {
                    readSettingBuilder.buildReadCardType(ReadCardType.USB_DK)
                }
                "3" -> {
                    readSettingBuilder.buildReadCardType(ReadCardType.USB_APDU)
                }
                else -> {
                    readSettingBuilder.buildReadCardType(ReadCardType.USB)
                }
            }
        }
        readCardManager.readCardInit(this)
    }

    override fun onResponse(code: Int, msg: String) {
        mHandler.post {
            if (code == StatusCode.ININ_ING.code) {
                appendLog("初始化中$code，$msg")
            } else if (code != StatusCode.ININ_OK.code) {
                initSuccess = false
                appendLog("初始化失败$code")
            } else {
                initSuccess = true
                appendLog("初始化成功，开始读卡")
                mHandler.postDelayed({
                    baseActivityBinding.tvVersion.apply {
                        text = "v${BuildConfig.VERSION_NAME}\n${DevicesUtils.getDeviceId(baseContext)}"
                        setTextIsSelectable(true)
                        append("\n读卡器版本：${readCardManager.readFirmwareVersion()},序列号：${Constant.hardwareNumber}")
                    }
                }, 1000)
                readCardManager.readCardStart(this)
            }
        }
    }

    /**
     * APDU读卡器寻卡成功的数据回调
     *
     * @param resultBytes  // 卡类型（ 1字节）+ UID长度（1字节）+ UID + 复位号长度（1字节）+ 复位号
     */
    override fun onAPDUFindCardSuccess(resultBytes: ByteArray?) {
        super.onAPDUFindCardSuccess(resultBytes)
        resultBytes?.let {
            // 卡类型
            val cardType = resultBytes[0]
            // 卡片 UID
            val uid = resultBytes.copyOfRange(2, 2 + resultBytes[1])
            appendLog("\nAPDU读卡器寻卡成功，卡类型：$cardType,UID：${BytesUtils.bytesToHexString(uid)}\n")

            // 判断卡类型
            when (cardType) {
                0x00.toByte() -> { // 根据类型操作卡
                    // 发送APDU指令
                    val apdu = byteArrayOf(
                        0x00, 0xA4.toByte(), 0x04, 0x00, 0x07,
                        0xA0.toByte(), 0x00, 0x00, 0x00, 0x03,
                        0x00, 0x00, 0x00
                    )
                    val result = UsbHidDevice.getInstance().sendAPDUWithReturn(apdu, 500)
                    if (result != null) {
                        // 处理返回数据
                    }
                }
                else -> {}
            }

            // 自己处理结束，继续执行寻卡读卡
            readCardManager.readCardStart(this)
        }
    }
}